package com.cinemate;

import android.util.Log;
import com.cinemate.Entities.APIs;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.*;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;

public class HttpUtil {

    public DefaultHttpClient client;
    public HttpResponse resp;
    public String respContent;
    public HttpGet get;
    public HttpPost post;

    public String ConvertStreamtoString(InputStream stream) {

        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader reader = null;

            reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("windows-1251")));
            String line;

            while ((line = reader.readLine()) != null) {
                builder.append(line).append("\n");
            }


            reader.close();
        } catch (UnsupportedEncodingException e) {
        } catch (IOException ex) {
        }

        return builder.toString();
    }

    public String LoginAndGetPasskey(String username, String password){
        String result = "";

        try{
            client = new DefaultHttpClient();
            get = new HttpGet(APIs.account_auth.replace("USERNAME", username).replace("PASSWORD", password));

            resp = client.execute(get);
            String response = ConvertStreamtoString(resp.getEntity().getContent());

            int statusCode = resp.getStatusLine().getStatusCode();

            if (statusCode == 200){
                JSONObject object = new JSONObject(response);
                result = object.getString("passkey");
            }


        }
        catch(Exception ex){
            Log.e("GET PASSKEY", ex.getMessage());
        }
        finally{

        }

        return result;
    }


}
